//
//  BaseViewModel.m
//  XBFrameworkProject
//
//  Created by 徐秀滨 on 2018/11/12.
//  Copyright © 2018 徐秀滨. All rights reserved.
//

#import "NetworkViewModel.h"
#import <AFNetworking.h>

typedef enum : NSUInteger {
    XBErrorServerNotConnection =-1004,//服务器连接失败。
    XBErrorServerNotReachable =-1009,//网络不可用。
    XBErrorClosedNetwork = -1018,//关闭网络
    XBErrorServerIsBusy = 3840//服务繁忙
} ZoeError;

@implementation NetworkViewModel

#pragma mark - AFNetworking调用

- (void)networkRequest:(NSString*)url
            parameters:(id)parameters
                  type:(NetworkRequestType)requestType
          successBlock:(void(^)(void))successBlock
          failureBlock:(void(^)(void))failureBlock {
    
    UIApplication *app = [UIApplication sharedApplication];
    dispatch_async(dispatch_get_main_queue(), ^{
        app.networkActivityIndicatorVisible = YES;
    });
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded;charset=utf-8;application/json;" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 120.0;
    
    //https证书验证部分
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = NO;
    manager.securityPolicy = securityPolicy;
    
    //请求头部
    if ([FrameworkSharedInstance sharedInstance].networkHeader) {
        NSArray *allKeys = [[FrameworkSharedInstance sharedInstance].networkHeader allKeys];
        for (NSString *keySting in allKeys) {
            [manager.requestSerializer setValue:[[FrameworkSharedInstance sharedInstance].networkHeader valueForKey:keySting] forHTTPHeaderField:keySting];
        }
    }
    
    if(requestType == NetworkRequestPost){
        [manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress){
            //coding……
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject){
            dispatch_async(dispatch_get_main_queue(), ^{
                app.networkActivityIndicatorVisible = NO;
            });
            [self dealResponseData:responseObject];
            if(successBlock){
                successBlock();
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                app.networkActivityIndicatorVisible = NO;
            });
            self.isSuccess = NO;
            self.errorMsg = resolveError(error);
            if(failureBlock){
                failureBlock();
            }
        }];
    }else {
        [manager GET:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
            //coding……
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            dispatch_async(dispatch_get_main_queue(), ^{
                app.networkActivityIndicatorVisible = NO;
            });
            [self dealResponseData:responseObject];
            if(successBlock){
                successBlock();
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                app.networkActivityIndicatorVisible = NO;
            });
            self.isSuccess = NO;
            self.errorMsg = resolveError(error);
            if(failureBlock){
                failureBlock();
            }
        }];
        
    }
}

#pragma mark - 辅助

- (void)dealResponseData:(id)responseObject {
    NSDictionary *responseData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
    NSString *code = [NSString stringWithFormat:@"%@",[responseData valueForKey:@"code"]];
    if([code isEqualToString:@"0"]){
        self.isSuccess = YES;
        id data = [responseData valueForKey:@"data"];
        if([data isKindOfClass:[NSArray class]]){
            self.dataArray = data;
        }else if([data isKindOfClass:[NSDictionary class]]){
            self.dataItem = data;
        }else if(data != [NSNull null]){
            self.dataExtend = data;
        }
    }else{
        self.isSuccess = NO;
        if([responseData valueForKey:@"message"] == [NSNull null]){
            self.errorMsg = @"";
        }else{
            self.errorMsg = [responseData valueForKey:@"message"];
        }
    }
}

NSString* resolveError(NSError*error) {
    NSString *errorInfo = [error localizedDescription];
    if (!errorInfo.length) {
        errorInfo = @"请求服务失败！";
    }
    switch (error.code) {
            case XBErrorServerNotReachable:
            errorInfo = @"网络链接失败，请检查网络是否开启！";
            break;
            case XBErrorServerNotConnection:
            errorInfo = @"请求服务失败！";
            break;
            case XBErrorClosedNetwork:
            errorInfo = @"无网络，请检查网络是否开启!";
            break;
            case XBErrorServerIsBusy:
            errorInfo = @"服务繁忙，请稍候重试!";
            break;
        default:
            break;
    };
    return errorInfo;
}

@end
